package com.xiaochuan.controller;


import com.xiaochuan.mapper.UserSysPrivilegeMapper;
import com.xiaochuan.pojo.User;
import com.xiaochuan.pojo.UserSysPrivilege;
import com.xiaochuan.utils.ResultBody;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.TreeSet;

/**
 * <p>
 * 用户账户表 前端控制器
 * </p>
 *
 * @author 经典
 * @since 2021-04-21
 */

@RestController
@Api(value = "用户登录")
public class UserController {

    @Resource
    private UserSysPrivilegeMapper userSysPrivilegeMapper;

    private static Logger log = LoggerFactory.getLogger(UserController.class);


    @PostMapping(value = "login",produces = {"application/json;charset=UTF-8"})
    public ResultBody login(@RequestBody User user){
        log.info("参数 "+user);
        Subject subject = SecurityUtils.getSubject();//获取当前登录对象
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserAccount().trim(),user.getUserPassword().trim());
        try {
            subject.login(usernamePasswordToken);//验证登录
            TreeSet<UserSysPrivilege> userSysPrivilege=userSysPrivilegeMapper.selectUserSysPrivilegeType(usernamePasswordToken.getUsername());

            Object principal = SecurityUtils.getSubject().getPrincipal();
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("userSysPrivilege",userSysPrivilege);
            hashMap.put("principal",principal);
            return ResultBody.success(hashMap);
        }catch (UnknownAccountException uae ) {
            return ResultBody.error("用户名不存在");
        } catch (IncorrectCredentialsException ice ) {
            return ResultBody.error("密码错误");
        } catch (LockedAccountException lae) {
            return ResultBody.error("用户被锁定  不能登录");
        } catch (AuthenticationException ae ) {
            return ResultBody.error("严重的错误");
        }

    }

}

